<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\CommodityLabel;
use Illuminate\Http\Request;

class CommodityLabelController extends Controller
{
    public function store(Request $request)
    {
        $commodityLabel = CommodityLabel::query()->create($request->only(['name', 'sort_id']));
        $commodityLabel->attachments()->sync($request->get('pic'));

        return $this->response->created(null, $commodityLabel);
    }

    public function list()
    {
        return $this->response->array(
            CommodityLabel::query()
                ->with('attachments')
                ->paginate()
        );
    }

    public function delete($id)
    {
        CommodityLabel::query()->findOrFail($id)->delete();

        return $this->response->noContent();
    }

    public function update(Request $request, $id)
    {
        $label = CommodityLabel::query()->findOrFail($id);
        $label->update([
            'name' => $request->get('name', $label['name']),
            'sort_id' => $request->get('sort_id', $label['sort_id'])
        ]);
        if (!empty($request->get('pic'))) {
            $label->attachments()->sync($request->get('pic'));
        }

        return $this->response->created(null, $label);
    }
}
